package com.scsystem.xysc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scsystem.xysc.aop.LogOperations;
import com.scsystem.xysc.pojo.Order;
import com.scsystem.xysc.pojo.Product;
import com.scsystem.xysc.pojo.Store;
import com.scsystem.xysc.pojo.User;
import com.scsystem.xysc.pojo.vo.ReturnResult;
import com.scsystem.xysc.service.OrderService;
import com.scsystem.xysc.service.ProductService;
import com.scsystem.xysc.service.StoreService;
import com.scsystem.xysc.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/store")
@CrossOrigin
@Tag(name = "商家接口")
public class StoreController {

    @Resource
    private StoreService storeService;
    @Resource
    private UserService userService;
    @Resource
    private ProductService productService;
    @Resource
    private OrderService orderService;



    @PostMapping("/login")
    @Operation(summary = "商家登录")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "password", description = "密码")
    })
    public ReturnResult<Store> businessLogin(@RequestParam("username") String username,
                                             @RequestParam("password") String password,
                                             HttpServletRequest request) {
        User user = userService.getOne(new QueryWrapper<User>().eq("user_name", username)
                .eq("password", password));
        if (user == null) {
            return new ReturnResult<>(400, "无该用户");
        }
        Store storeUser = storeService.getOne(new QueryWrapper<Store>().eq("user_id", user.getUserId()));
        if (storeUser == null) {
            return new ReturnResult<>(400, "该用户未注册成为商家");
        }

        HttpSession session = request.getSession();
        session.setAttribute("userId", storeUser.getUserId());
        session.setAttribute("userType", "商家");

        return new ReturnResult<>(200, "登录成功", storeUser);
    }


    @PostMapping("/register")
    @Operation(summary = "商家注册")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "password", description = "密码"),
            @Parameter(name = "storeName", description = "店铺名称"),
            @Parameter(name = "storeDescription", description = "店铺简介")
    })
    @LogOperations(module = "商家", operation = "商家注册")
    public ReturnResult<Boolean> register(@RequestParam("username") String username,
                                        @RequestParam("password") String password,
                                        @RequestParam("storeName") String storeName,
                                        @RequestParam("storeDescription") String storeDescription,
                                        HttpServletRequest request) {
        User user = userService.getOne(new QueryWrapper<User>().eq("user_name", username)
                .eq("password", password));
        if (user == null) {
            return new ReturnResult<>(400, "无该用户，请先注册成为正式用户", false);
        } else if (storeService.getOne(new QueryWrapper<Store>().eq("user_id", user.getUserId())) != null) {
            return new ReturnResult<>(400, "注册失败，重复注册", true);
        }

        Store store = new Store();
        store.setStoreName(storeName);
        store.setUserId(user.getUserId());
        store.setStoreDescription(storeDescription);
        store.setCreateTime(LocalDateTime.now());
        store.setStoreStatus("正常");

        if (storeService.save(store)) {
            HttpSession session = request.getSession();
            session.setAttribute("userId", store.getUserId());
            session.setAttribute("userType", "商家");

            return new ReturnResult<>(200, "注册成功，请登录", true);
        }else {
            return new ReturnResult<>(400, "注册失败", false);
        }
    }

    @GetMapping("/ban")
    @LogOperations(module = "商家", operation = "对商家进行封禁或解封")
    @Operation(summary = "对商家进行封禁或解封")
    @Parameter(name = "storeId", description = "店铺ID")
    public ReturnResult<Boolean> banStore(@RequestParam("storeId") long storeId) {
        Store store = storeService.getById(storeId);
        if ("封禁".equals(store.getStoreStatus())){
            store.setStoreStatus("正常");
        }else {
            store.setStoreStatus("封禁");
        }
        if (storeService.updateById(store)){
            return new ReturnResult<>(200, "操作成功",Boolean.TRUE);
        }else{
            return new ReturnResult<>(400, "操作失败",Boolean.FALSE);
        }
    }

    @PostMapping ("/ban")
    @LogOperations(module = "商家", operation = "修改商家信息")
    @Operation(summary = "修改商家信息")
    @Parameter(name = "store", description = "修改后的对象")
    public ReturnResult<Boolean> updateStore(@RequestBody Store store) {
        if (storeService.updateById(store)){
            return new ReturnResult<>(200, "修改成功",Boolean.TRUE);
        }else{
            return new ReturnResult<>(400, "修改失败",Boolean.FALSE);
        }
    }

    @GetMapping("/getStoreProduct")
    @Operation(summary = "获取该店铺的全部商品")
    @Parameter(name = "sid", description = "店铺id")
    public ReturnResult<List<Product>> getStoreProduct(Long sid) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", sid);
        List<Product> list = productService.list(queryWrapper);
        if (list.isEmpty())
            return new ReturnResult<>(400, "该店铺无商品数据");
        else
            return new ReturnResult<>(200, "获取成功", list);
    }

    @GetMapping("/getStoreOrder")
    @Operation(summary = "获取该店铺的全部订单")
    @Parameter(name = "sid", description = "店铺id")
    public ReturnResult<List<Order>> getStoreOrder(Long sid) {
        ReturnResult<List<Product>> storeProduct = getStoreProduct(sid);
        if (storeProduct.getCode() == 400)
            return new ReturnResult<>(400, "该商铺无订单");

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        for(int i = 0; i < storeProduct.getData().size(); i++) {
            queryWrapper.eq("product_id", storeProduct.getData().get(i).getProductId()).or();
        }

        List<Order> list = orderService.list(queryWrapper);
        if (list.isEmpty())
            return new ReturnResult<>(400, "该商铺无订单");
        else
            return new ReturnResult<>(200, "获取成功", list);
    }

}
